package org.lmj.dos.web.controller;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lmj.dos.common.bean.ServerResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


@RestController
@Slf4j
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    private String bucket="D://opt/bucket";



    @SneakyThrows
    @PostMapping("/upload")
    public ServerResponse upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
       // String xxx = request.getParameter("xxx");
        //获取所需参数，再进行数据库相关操作
        String originalFilename = file.getOriginalFilename();
        String uniFileName = UUID.randomUUID().toString();
        File file1 = new File(bucket);
        if (!file1.exists()) {
            if (file1.mkdirs()) {
                log.info("makedir success, dir path{}", bucket);
            } else {
                log.error("makedir error, dir path{}", bucket);
            }
        }
        File dest = new File(bucket +"/"+ uniFileName);
        file.transferTo(dest);
        return ServerResponse.success(uniFileName);
    }

    @SneakyThrows
    @GetMapping("/download")
    public void upload(HttpServletResponse response, String uniFileName) {
         String s = bucket + "/" + uniFileName;
        byte[] bytes = getBytes(s);
        response.addHeader("Accept-Ranges", "bytes");
        response.setStatus(200);
        response.setContentType("application/octet-stream");
        //从数据库里面查到getOriginalFileName
//        response.addHeader("Content-disposition", "attachment;filename="
//                + new String("blog.png".getBytes("UTF-8"), "ISO-8859-1"));
        response.getOutputStream().write(bytes);
    }


    /**
     * 删除的话就是删除表记录就行，没必要进行物理删除
     * @param fileId
     * @return
     */
    @SneakyThrows
    @GetMapping("/delete/{fileId}")
    public ServerResponse delete(@PathVariable(name = "fileId") String fileId) {
        return ServerResponse.success("success");
    }

    public  byte[] getBytes(String filePath) {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            log.error("" + e);
        } catch (IOException e) {
            log.error("" + e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("close stream error");
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error("close stream error");
                }
            }
        }
        return buffer;
    }

}
